/*
	@author 张成
	@description 网络请求工具类
 */
import {
	getStorage
} from "./util";

const BaseUrl = process.uniEnv.BaseUrl;
const Active = process.uniEnv.Active;

/**
 * 未定义接口地址的request
 * @param {*} url
 * @param {*} method
 * @param {*} data
 * @param {*} header
 */
const request = (url, method, data = {}, header = {}) => {
	let promise = new Promise(function(resolve, reject) {
		wx.request({
			url: url,
			data: data,
			method: method,
			header: header,
			success(data) {
				resolve(data);
			},
			fail(data) {
				reject(data);
			},
		});
	});

	return promise;
};


/**
 * 定义了接口地址的request
 * @param {*} url
 * @param {*} method
 * @param {*} data
 * @param {*} header
 */
const requestBase = (url, method, data = {}, header = {}) => {
	return new Promise((resolve, reject) => {
		wx.request({
			url: BaseUrl + url,
			data: data,
			method: method,
			header: header,
			success(data) {
				resolve(data);
			},
			fail(error) {
				reject(error);
			},
		});
	});
};
/**
 * 携带认证头部的请求
 * @param {*} url
 * @param {*} method
 * @param {*} data
 */
const requestAuth = (url, method, data = {}) => {
	return new Promise((resolve, reject) => {
		//获取Toekn
		let token = getStorage("token");
		let header = {
			"Authorization": "Bearer " + token,
		};
		//发送请求
		wx.request({
			url: BaseUrl + url,
			data: data,
			method: method,
			header: header,
			success(data) {
				resolve(data);
			},
			fail(error) {
				reject(error);
			},
		});
	});
};

const getImg = (path) => {
	return new Promise((resolve, reject) => {
		//获取Toekn
		let token = getStorage("token");
		let header = {
			"Authorization": "Bearer " + token,
		};
		//发送请求
		wx.downloadFile({
			url: BaseUrl + 'system/file/show_pic?path=' + path,
			header: header,
			success(data) {
				resolve(data.tempFilePath);
			},
			fail(error) {
				reject(error);
			},
		});
	});
}

module.exports = {
	request,
	requestBase,
	requestAuth,
	BaseUrl,
	Active,
	getImg
};
